#include "Sprite.h"

CSprite::CSprite(void)
{
	gd3dDevice->CreateIndexBuffer(6*sizeof(DWORD), D3DUSAGE_WRITEONLY,
		D3DFMT_INDEX16, D3DPOOL_MANAGED, &mIB, 0);

	WORD* k = 0;
	mIB->Lock(0, 0, (void**) &k, 0);

	k[0] = 0;
	k[1] = 3;
	k[2] = 2;
	k[3] = 0;
 	k[4] = 2;
	k[5] = 1;

	mIB->Unlock();
}

CSprite::CSprite(int texId)
{
	CSprite();
	SetTexture(texId);
}

CSprite::~CSprite(void)
{
	ReleaseCOM(mVB);
	ReleaseCOM(mIB);
}


void CSprite::SetTexture(int texId, float left, float top, float right, float bottom)
{	
	m_Tex = ResourceManager::GetInstance()->getTextureByID(texId);
	m_TexRect = CRect(left, top, right, bottom);
}

void CSprite::SetTexture(int id)
{
	SetTexture(id, 0.0f, 0.0f, 1.0f, 1.0f);
}

void CSprite::Render()
{
	// convert windows to directx coordinate	
	RECT formatRect;
	GetClientRect(gd3dApp->getMainWnd(), &formatRect);

	float top, bottom, left, right;

	WindowsToDirectXCoord(&formatRect, m_Border.left, m_Border.top, left, bottom);
	WindowsToDirectXCoord(&formatRect, m_Border.right, m_Border.bottom, right, top);
	
	m_Border.SetRect(left, top, right, bottom);

	BuildVertexBuffer();

	gd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
	gd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
	gd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
	//gd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
	//gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
	//gd3dDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DRS_DESTBLENDALPHA);

	//sgd3dDevice->sette

	gd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
	gd3dDevice->SetTexture( 0, m_Tex );

	gd3dDevice->SetStreamSource(0, mVB, 0, sizeof(VertexPT));
	gd3dDevice->SetIndices(mIB);	

	gd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 6, 0, 2);
}

void CSprite::Render(CRect* r, CRect* texCoord)
{
	memcpy(&m_TexRect, texCoord, sizeof(CRect));
	memcpy(&m_Border, r, sizeof(CRect));
	Render();
}

void CSprite::BuildVertexBuffer()
{
	gd3dDevice->CreateVertexBuffer(4 * sizeof (VertexPT),
		0, D3DFVF_CUSTOMVERTEX, D3DPOOL_MANAGED, &mVB, 0);

	VertexPT* v = 0;
	mVB->Lock(0, 0, (void**) &v, 0);

	v[0] = VertexPT(m_Border.left, m_Border.top, 0.0f, m_TexRect.left, m_TexRect.bottom );
	v[1] = VertexPT(m_Border.left, m_Border.bottom, 0.0f,m_TexRect.left, m_TexRect.top  );
	v[2] = VertexPT(m_Border.right, m_Border.bottom, 0.0f,m_TexRect.right, m_TexRect.top );
	v[3] = VertexPT(m_Border.right, m_Border.top, 0.0f, m_TexRect.right, m_TexRect.bottom );

	mVB->Unlock();

}

void CSprite::SetBorder(CRect* r) 
{ 
	memcpy(&m_Border, r, sizeof(CRect));
}